﻿using System;
using System.Linq;
using System.IO;
using System.Reflection;
using AChance.Bll.Func;
using AChance.Bll.Trans;
using AChance.Dal.Func;
using AChance.Func;
using FutureSerWeb.Func;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using AChance.Dal.Entity;
using Microsoft.AspNetCore.Http;

namespace FutureSerWeb
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            FunContext.AppSettings.Init(Configuration);
            services.AddHttpClient();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddControllers(options =>
            {
                //options.Filters.Add(typeof(AppFilters.Authorization.GlobalFilter));
                //options.Filters.Add(typeof(AppFilters.Action.GlobalFilter));
            }
            ).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            }
            ).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(AppConst.App.VER, new OpenApiInfo
                {
                    Title = AppConst.App.NAME,
                    Version = AppConst.App.VER,
                    Description = AppConst.App.DESC
                });
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"), true);
            });
            services.AddSwaggerGenNewtonsoftSupport();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lif)
        {
            try
            {
                FunContext.Services.Init(app.ApplicationServices);
                //初始化临时目录
                if (!FunTemp.Init())
                    throw new Exception("初始化临时目录失败");
                //初始化文件目录
                if (!FunFiles.Init())
                    throw new Exception("初始化文件目录失败");
                ////更新数据库结构
                //BllTrans.Invoke<TrnSql.ChgStruct>();
                ////更新数据库索引
                //BllTrans.Invoke<TrnSql.ChgIndex>();
                ////更新数据库视图
                //BllTrans.Invoke<TrnSql.ChgView>();
                ////更新数据库存储过程
                //BllTrans.Invoke<TrnSql.ChgProc>();
                ////更新数据库触发器
                //BllTrans.Invoke<TrnSql.ChgTrigger>();
                ////更新缓存信息
                //BllTrans.Invoke<TrnSql.ChgCache>();
                ////校验机构信息
                //if (!BllCache.Organ.Check())
                //    throw new Exception("校验机构信息失败");
                FunContext.OrganNo = BllCache.Organ.GetNo();
                //创建Redis用户
                BllTrans.Invoke<TrnRedis.AddUser>();
                //启动线程
                if (!FunTask.Get(FunTask.Name.SYSTEM).Start(AppTask.System))
                    throw new Exception("启动系统线程失败");
                //if (!FunTask.Get(FunTask.Name.BUSINESS).Start(FunIdv.Get<Action>(AppTask.Business)))
                //    throw new Exception("启动业务线程失败");

                //配置服务
                //if (env.IsDevelopment())
                //{
                //    app.UseDeveloperExceptionPage();
                //}
                //else
                //{
                //    app.UseExceptionHandler("/error");
                //}
                app.UseStaticFiles();
                app.UseRouting();
                //app.Use(next => context =>
                //{
                //    context.Request.EnableBuffering();
                //    return next(context);
                //});
                app.UseCors(builder =>
                {
                    builder.WithOrigins(FunContext.AppSettings.Cors.AllowOrigins)
                                .WithMethods(FunContext.AppSettings.Cors.AllowMethods)
                                .WithHeaders(FunContext.AppSettings.Cors.AllowHeaders)
                                .AllowCredentials();
                });
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    if (FunContext.AppSettings.Console.Visible)
                    {
                        endpoints.MapRazorPages();
                        endpoints.MapBlazorHub();
                        //endpoints.MapFallbackToPage("/Console/_Host");
                    }
                });
                app.UseSwagger();
                app.UseSwaggerUI(options =>
                {
                    options.SwaggerEndpoint($"/swagger/{AppConst.App.VER}/swagger.json", AppConst.App.NAME);
                    options.RoutePrefix = string.Empty;
                });
                lif.ApplicationStopped.Register(() =>
                {
                    try
                    {
                        //停止所有线程
                        if (!FunTask.Stop())
                            throw new Exception("停止所有线程失败");

                        FunLogs.LogInfo("系统停止成功");
                    }
                    catch (Exception ex)
                    {
                        FunLogs.LogError("系统停止失败", ex);
                    }
                });

                FunContext.IsStartSuccess = true;
                FunLogs.LogInfo("系统启动成功");
            }
            catch (Exception ex)
            {
                FunContext.IsStartSuccess = false;
                FunLogs.LogError("系统启动失败", ex);
            }

            //try
            //{
            //    //object aa = "";
            //    //aa = 0;
            //DalOper.Sql.Open(true);
            //    //FDWBDR abc = new FDWBDR()
            //    //{
            //    //    BDRNAME = "ffffffaa111aaf"
            //    //};
            //    // DalEntity.RepairDefault(abc);


            //    //BllBiz.DataPkg dataPkg = new BllBiz.DataPkg();
            //    //// object sss=dataPkg.InData.abc;
            //    //dataPkg.InData["BDR"] = 1;
            //    //BllOper.Trans.Invoke<TrnBuilder.UpdateAdd>(dataPkg);
            //    //var ewr = dataPkg.OutData["BDR"];
            //string aaa =null;
            //aaa = aaa.ToSqlArg();
            //FDWORG abc = new FDWORG();
            //abc.ORGTYPE = "s";
            //var aa = (from u in DalOper.Sql.Ext.FDWORG select u)
            //    .Where(oRG=>oRG.ORGID.Equals(abc.ORGTYPE))
            //    .Select(aa => aa.ORGADDR).Take(1).ToRawSql();

            //var www = "";
            //    //aa[0]["ORGID"] = "ffff";
            //    //var aa = DalOper.Sql.ExecDDL("ALTER TABLE FDWORG ADD FAROUTMODE VARCHAR (1)");
            //    //string aa = "select * from fdworg where orgnaame=" + "厦门市建设局".ToSqlArgs();
            //    //DalOper.Sql.Select(aa);
            //    //string aa = $"INSERT INTO [FDWORG] ([ORGID], [ORGADDR], [ORGCONSULTPHONE], [ORGNAME], [ORGTYPE], [ORGZIPCODE]) VALUES({"3502001D1F1".ToSqlArgs()}, '1厦禾路362号建设大厦', '7703876   8123035   8123014', '厦门市建设局', '', '361000')";
            //    //DalOper.Sql.Insert(aa);
            //    //DalOper.Sql.Delete(new List<FDWORG>() { });
            //    //var ww = DalOper.Sql.Select<FDWORG>("350200D1F1");
            //    //ww.ORGNAME = "厦门市建设局";
            //    FDWORG entORG = new FDWORG()
            //    {
            //        ORGID = "330322X2F1",
            //        ORGNAME = "厦门市建设局123",
            //        ORGADDR = "厦禾路362号建设大厦"
            //    };
            //    FDWORG entORGa = new FDWORG()
            //    {
            //        ORGID = "350200D1F1",
            //        ORGNAME = "厦门市建设局123",
            //        ORGADDR = "厦禾路362号建设大厦ab1",
            //        ORGCONSULTPHONE = "",
            //        ORGTYPE = "1",
            //        ORGZIPCODE = "",
            //        ORGSTATUS = (DalState.ORGSTATUS)12,
            //        EXTORGABC = "sdfsdf"
            //    };
            //    var aaa = DalEntity.GetWhereSql<FDWORG>(null);
            //    FDWORG entORGaa = new FDWORG()
            //    {
            //        ORGID = "350200D1F1",
            //        ORGNAME = "fffffffff",
            //        ORGADDR = "eeeeeeeeee"
            //    };
            //    //var ss = DalOper.Sql.Update(entORGaa, aaa => new { aaa.ORGNAME });
            //    //var proc = new DalQuery.Proc();
            //    //proc.SelectSum.Add(new DalQuery.SelectProc.Condition() { Name = "ACLPRINCIPAL" });
            //    //proc.PageIndex = 1;
            //    //proc.PageSize = 10;
            //    //var ff = DalOper.Sql.SelectProc("select  * from fdworg", null, default);
            //    var fff = DalOper.Sql.Insert(entORGa);
            //    //var faf = DalOper.Sql.Delete(new List<FDWORG>() { entORGa });
            //    //var ff = DalOper.Sql.SelectCount<FDWORG>(null);
            //    //var ggg = DalOper.Sql.Select(entORGa);
            //    //var fff = DalOper.Sql.Delete(new List<FDWORG>() { entORG, entORGa });
            //    //var qqq = DalOper.Sql.Update(entORG, abc => new { abc.ORGADDR });
            //    //var qqq = DalOper.Sql.Update("update fdworg set orgid=" + "350200D1F1".ToSqlArg());
            //    //var qq = DalOper.Sql.Update(entORG, abc => abc.ORGADDR);
            //    //var qq = DalOper.Sql.UpdateRange<FDWORG>(abc => new FDWORG() { ORGNAME = "维修资金管理中心1234" }, aa => aa.ORGADDR == "厦禾路362号建设大厦ab1");
            //    //var ee = DalOper.Sql.Update(entORGa);
            //    //var ee = DalOper.Sql.Update(entORG);
            //    //var sss = DalOper.Sql.SelectFirst<FDWORG>(aa => aa.ORGSTATUS == 0);
            //    //var ff = DalOper.Sql.Delete<FDWORG>(aa=>aa.ORGNAME=="1sss");
            //    DalOper.Sql.Close(true);
            //}
            //catch (Exception ex)
            //{
            //    DalOper.Sql.Close();
            //    throw ex;
            //}

        }
    }
}
